import {makeAutoObservable, runInAction} from 'mobx';
import {IPage} from "./PageStore";
import {pageStore} from "./index";

export interface IPageEditorStore {
    isPreview: boolean;
    isMobile: boolean;
    currPageId?: string;
    schema?: any;

    setPreview(isPreview: boolean): void;

    setIsMobile(isMobile: boolean): void;

    setSchema(schema: string): void;

    setCurrPageId(pageId: string): void;

    save(): void;
}

export class PageEditorStore implements IPageEditorStore {

    isPreview: boolean = false;
    isMobile: boolean = false;
    currPageId = 'root';
    schema?: any;

    constructor() {
        makeAutoObservable(this);
    }

    setPreview(isPreview: boolean): void {
        this.isPreview = isPreview
    }

    setIsMobile(isMobile: boolean): void {
        this.isMobile = isMobile
    }

    setSchema(schema: string): void {
        this.schema = schema
    }

    setCurrPageId(currPageId: string): void {
        this.currPageId = currPageId
        let page = pageStore.getById(currPageId)

        this.setSchema(page?.schema)
    }

    save(): void {
        let page = pageStore.getById(this.currPageId)
        if (page) {
            page.schema = this.fixJsonUrl(this.schema)
            pageStore.update(page)
        }
    }

    fixJsonUrl(schema: any): any {
        const fixCrud = (json: any): any => {
            if (json instanceof Array) {
                json.forEach((item: any) => fixCrud(item))
            } else if (json instanceof Object) {
                if (json && json.type) {
                    if (json.type == "crud" && json.api && json.api.hasOwnProperty("url")) {
                        if (!json.api.url || json.api.url == "") {
                            json.api.url = "app/datas/crud"
                        }
                    } else if (json.type == "form" && json.api && json.api.hasOwnProperty("url")) {
                        console.log(json)
                        if (!json.api.url || json.api.url == "") {
                            json.api.url = "app/datas/update"
                        }
                    }
                }

                Object.getOwnPropertyNames(json).forEach((key: any) => fixCrud(json[key]))
            }
        }

        if (schema) {


            fixCrud(schema)

            let schemaStr = JSON.stringify(schema);
            schemaStr = schemaStr.replace(new RegExp("xxx/update", "gm"), "app/datas/update")
            schemaStr = schemaStr.replace(new RegExp("/xxx/batch-delete", "gm"), "app/datas/batch-delete")
            schemaStr = schemaStr.replace(new RegExp("/xxx/bacth-edit", "gm"), "app/datas/batch-edit")

            schema = JSON.parse(schemaStr)
        }

        return schema
    }

}